#pragma once
/// @brief 工具类
#include "../server.hpp"
#include <fstream>
#include <regex>
#define DEFAULT_TIME_OUT 10
std::unordered_map<int, std::string> _statu_msg = {
    {100, "Continue"},
    {101, "Switching Protocol"},
    {102, "Processing"},
    {103, "Early Hints"},
    {200, "OK"},
    {201, "Created"},
    {202, "Accepted"},
    {203, "Non-Authoritative Information"},
    {204, "No Content"},
    {205, "Reset Content"},
    {206, "Partial Content"},
    {207, "Multi-Status"},
    {208, "Already Reported"},
    {226, "IM Used"},
    {300, "Multiple Choice"},
    {301, "Moved Permanently"},
    {302, "Found"},
    {303, "See Other"},
    {304, "Not Modified"},
    {305, "Use Proxy"},
    {306, "unused"},
    {307, "Temporary Redirect"},
    {308, "Permanent Redirect"},
    {400, "Bad Request"},
    {401, "Unauthorized"},
    {402, "Payment Required"},
    {403, "Forbidden"},
    {404, "Not Found"},
    {405, "Method Not Allowed"},
    {406, "Not Acceptable"},
    {407, "Proxy Authentication Required"},
    {408, "Request Timeout"},
    {409, "Conflict"},
    {410, "Gone"},
    {411, "Length Required"},
    {412, "Precondition Failed"},
    {413, "Payload Too Large"},
    {414, "URI Too Long"},
    {415, "Unsupported Media Type"},
    {416, "Range Not Satisfiable"},
    {417, "Expectation Failed"},
    {418, "I'm a teapot"},
    {421, "Misdirected Request"},
    {422, "Unprocessable Entity"},
    {423, "Locked"},
    {424, "Failed Dependency"},
    {425, "Too Early"},
    {426, "Upgrade Required"},
    {428, "Precondition Required"},
    {429, "Too Many Requests"},
    {431, "Request Header Fields Too Large"},
    {451, "Unavailable For Legal Reasons"},
    {501, "Not Implemented"},
    {502, "Bad Gateway"},
    {503, "Service Unavailable"},
    {504, "Gateway Timeout"},
    {505, "HTTP Version Not Supported"},
    {506, "Variant Also Negotiates"},
    {507, "Insufficient Storage"},
    {508, "Loop Detected"},
    {510, "Not Extended"},
    {511, "Network Authentication Required"}};

std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac", "audio/aac"},
    {".abw", "application/x-abiword"},
    {".arc", "application/x-freearc"},
    {".avi", "video/x-msvideo"},
    {".azw", "application/vnd.amazon.ebook"},
    {".bin", "application/octet-stream"},
    {".bmp", "image/bmp"},
    {".bz", "application/x-bzip"},
    {".bz2", "application/x-bzip2"},
    {".csh", "application/x-csh"},
    {".css", "text/css"},
    {".csv", "text/csv"},
    {".doc", "application/msword"},
    {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot", "application/vnd.ms-fontobject"},
    {".epub", "application/epub+zip"},
    {".gif", "image/gif"},
    {".htm", "text/html"},
    {".html", "text/html"},
    {".ico", "image/vnd.microsoft.icon"},
    {".ics", "text/calendar"},
    {".jar", "application/java-archive"},
    {".jpeg", "image/jpeg"},
    {".jpg", "image/jpeg"},
    {".js", "text/javascript"},
    {".json", "application/json"},
    {".jsonld", "application/ld+json"},
    {".mid", "audio/midi"},
    {".midi", "audio/x-midi"},
    {".mjs", "text/javascript"},
    {".mp3", "audio/mpeg"},
    {".mpeg", "video/mpeg"},
    {".mpkg", "application/vnd.apple.installer+xml"},
    {".odp", "application/vnd.oasis.opendocument.presentation"},
    {".ods", "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt", "application/vnd.oasis.opendocument.text"},
    {".oga", "audio/ogg"},
    {".ogv", "video/ogg"},
    {".ogx", "application/ogg"},
    {".otf", "font/otf"},
    {".png", "image/png"},
    {".pdf", "application/pdf"},
    {".ppt", "application/vnd.ms-powerpoint"},
    {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar", "application/x-rar-compressed"},
    {".rtf", "application/rtf"},
    {".sh", "application/x-sh"},
    {".svg", "image/svg+xml"},
    {".swf", "application/x-shockwave-flash"},
    {".tar", "application/x-tar"},
    {".tif", "image/tiff"},
    {".tiff", "image/tiff"},
    {".ttf", "font/ttf"},
    {".txt", "text/plain"},
    {".vsd", "application/vnd.visio"},
    {".wav", "audio/wav"},
    {".weba", "audio/webm"},
    {".webm", "video/webm"},
    {".webp", "image/webp"},
    {".woff", "font/woff"},
    {".woff2", "font/woff2"},
    {".xhtml", "application/xhtml+xml"},
    {".xls", "application/vnd.ms-excel"},
    {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml", "application/xml"},
    {".xul", "application/vnd.mozilla.xul+xml"},
    {".zip", "application/zip"},
    {".3gp", "video/3gpp"},
    {".3g2", "video/3gpp2"},
    {".7z", "application/x-7z-compressed"}};

class Util
{

public:
    /// @brief 将source按sep分割到arry
    /// @param source
    /// @param sep
    /// @param arry
    /// @return
    static size_t Split(const std::string source, const std::string sep, std::vector<std::string> *arry)
    {
        size_t offsert = 0;
        size_t pos = 0;
        size_t n = 0;
        while (offsert < source.size())
        {
            pos = source.find(sep.c_str(), offsert);
            if (pos != std::string::npos)
            {
                // 找到了
                n = pos - offsert;
                if (n == 0) // 无数据
                {
                    offsert = pos + sep.size();
                    continue;
                }
                arry->push_back(source.substr(offsert, n));
                offsert = pos + sep.size();
            }
            else
            {
                arry->push_back(source.substr(offsert));
                break;
            }
        }
        return arry->size();
    }

    static bool ReadFile(const std::string filename, std::string *buf)
    {
        std::ifstream ifs(filename, std::ios::binary); // binary 以二进制读取
        if (ifs.is_open() == false)
        {
            lg.logmessage(Error, "%d open file error %s", __LINE__, strerror(errno));
            return false;
        }
        ifs.seekg(0, ifs.end);
        size_t fsize = 0;
        fsize = ifs.tellg();
        ifs.seekg(0, ifs.beg);
        buf->resize(fsize);
        ifs.read(&(*buf)[0], fsize);
        if (ifs.good() == false)
        {
            lg.logmessage(Error, "%d read %s error %s", __LINE__, filename.c_str(), strerror(errno));
            return false;
        }
        ifs.close();
        return true;
    }

    static bool WriteFile(const std::string filename, const std::string &buf)
    {
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc); // trunc清空原有文件
        if (ofs.is_open() == false)
        {
            lg.logmessage(Error, "%d open file error %s", __LINE__, strerror(errno));
            return false;
        }
        ofs.write(buf.c_str(), buf.size());
        if (ofs.good() == false)
        {
            lg.logmessage(Error, "%d write %s error %s", __LINE__, filename.c_str(), strerror(errno));
            return false;
        }
        ofs.close();
        return true;
    }
    static bool IsRegular(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
            return false;
        return S_ISREG(st.st_mode);
    };

    static bool IsDirectory(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
            return false;
        return S_ISDIR(st.st_mode);
    }

    /// @brief ". - ~"字母与数字不编码
    ////@brief 空格转为+
    /// @param url
    /// @param convert_spae_to_plus
    /// @return
    static std::string UrlEncode(const std::string url, bool convert_spae_to_plus)
    {
        std::string res;
        for (auto c : url)
        {
            if (c == '.' || c == '-' || c == '~' || isalnum(c))
            {
                res += c;
            }
            else if (c == ' ' && convert_spae_to_plus)
            {
                res += '+';
            }
            else
            {
                char temp[4];
                snprintf(temp, 4, "%%%02x", c);
                res += temp;
            }
        }
        return res;
    }

    static int HexToI(char c)
    {
        if (c >= 'a' && c <= 'f')
        {
            return c - 'a' + 10;
        }
        else if (c >= 'A' && c <= 'F')
        {
            return c - 'A' + 10;
        }
        else if (c >= '0' && c <= '9')
        {
            return c - '0';
        }
    }

    static std::string UrlDecode(const std::string url, bool convert_plus_to_space)
    {
        std::string res;
        for (int i = 0; i < url.size(); i++)
        {
            if (url[i] == '%')
            {
                char v1 = HexToI(url[i + 1]) * 16;
                char v2 = HexToI(url[i + 2]);
                res += v1 + v2;
                i += 2;
            }
            else if (url[i] == '+' && convert_plus_to_space)
            {
                res += ' ';
            }
            else
            {
                res += url[i];
            }
        }
        return res;
    }

    static std::string DesStau(int des)
    {
        auto item = _statu_msg.find(des);
        if (item != _statu_msg.end())
        {
            return item->second;
        }
        return "Unknow";
    }

    // 根据文件后缀名获取文件mime
    static std::string ExtMime(const std::string &filename)
    {

        // a.b.txt  先获取文件扩展名
        size_t pos = filename.find_last_of('.');
        if (pos == std::string::npos)
        {
            return "application/octet-stream";
        }
        // 根据扩展名，获取mime
        std::string ext = filename.substr(pos);
        auto it = _mime_msg.find(ext);
        if (it == _mime_msg.end())
        {
            return "application/octet-stream";
        }
        return it->second;
    }

    static bool ValidPath(const std::string path)
    {
        std::vector<std::string> arry;
        Split(path, "/", &arry);
        int level = 0;
        for (auto item : arry)
        {
            if (item == "..")
            {
                level--;
                if (level < 0)
                    return false;
            }
            else
            {
                level++;
            }
        }
        return true;
    }
};

class HttpRequest
{
public:
    std::string _method;
    std::string _path;
    std::string _version;
    std::string _body;
    std::smatch _matchs; // 按正则表达式匹配的结果
    std::unordered_map<std::string, std::string> _headers;
    std::unordered_map<std::string, std::string> _params;

public:
    void Reset()
    {
        _method.clear();
        _path.clear();
        _version.clear();
        _body.clear();
        std::smatch sma;
        _matchs.swap(sma);
        _headers.clear();
        _params.clear();
    }
    void SetHeader(const std::string &key, const std::string val)
    {
        _headers.insert(std::make_pair(key, val));
    }
    bool HasHeader(const std::string &key)
    {
        auto item = _headers.find(key);
        if (item == _headers.end())
            return false;
        return true;
    }
    std::string GetHeader(const std::string key)
    {
        if (HasHeader(key))
        {
            return _headers[key];
        }
        return "";
    }
    void SetParam(const std::string &key, const std::string val)
    {
        _params.insert(std::make_pair(key, val));
    }
    bool HasParam(const std::string &key)
    {
        auto item = _params.find(key);
        if (item == _params.end())
            return false;
        return true;
    }
    std::string GetParam(const std::string key)
    {
        if (HasParam(key))
        {
            return _params[key];
        }
        return "";
    }

    size_t ContentLength()
    {
        if (HasHeader("Content-Length"))
        {
            return std::stol(_headers["Content-Length"]);
        }
        return 0;
    }

    bool Close()
    {
        if (HasHeader("Connection") && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }
};

class HttpResponse
{
public:
    int _statu;
    bool _redirect_flag; // 重定向标志位
    std::string _body;
    std::string _redirect_url; // 重定向位置
    std::unordered_map<std::string, std::string> _headers;

public:
    HttpResponse(int statu = 200) : _redirect_flag(false), _statu(statu) {}
    void Reset()
    {
        _statu = 200;
        _redirect_flag = false;
        _body.clear();
        _redirect_url.clear();
    }
    void SetHeader(const std::string &key, const std::string val)
    {
        _headers.insert(std::make_pair(key, val));
    }
    bool HasHeader(const std::string &key)
    {
        auto item = _headers.find(key);
        if (item == _headers.end())
            return false;
        return true;
    }
    std::string GetHeader(const std::string key)
    {
        if (HasHeader(key))
        {
            return _headers[key];
        }
        return "";
    }

    void SetContent(const std::string &body, const std::string type = "text/html")
    {
        _body = body;
        SetHeader("Content-Type", type);
    }

    void SetRedirect(const std::string &url, int statu = 302)
    {
        _redirect_url = url;
        _statu = statu;
        _redirect_flag = true;
    }

    bool Close()
    {
        if (HasHeader("Connection") && GetHeader("Connection") == "keep-alive")
            return false;
        return true;
    }
};

typedef enum
{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER
} HttpRecvStatu;

class HttpConntext
{
private:
    int _resp_statu;           // 响应状态码
    HttpRecvStatu _recv_statu; // 接受状态码
    HttpRequest _request;
#define MAX_LINE 8192
private:
    bool ParseHttpLine(const std::string &line)
    {
        std::smatch matches;
        std::regex e("(GET|HEAD|POST|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase);
        bool ret = std::regex_match(line, matches, e);
        if (ret == false)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400; // BAD REQUEST
            return false;
        }
        // 请求方法的获取
        _request._method = matches[1];
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper); // 将其转换为大写
        //  资源路径的获取
        _request._path = Util::UrlDecode(matches[2], false);
        // 协议版本的获取
        _request._version = matches[4];
        // 查询字符串的获取与处理
        std::vector<std::string> query_string_arry;
        std::string query_string = matches[3];
        // 查询字符串的格式 key=val&key=val....., 先以 & 符号进行分割，得到各个字串
        Util::Split(query_string, "&", &query_string_arry);
        // 针对各个字串，以 = 符号进行分割，得到key 和val， 得到之后也需要进行URL解码
        for (auto &str : query_string_arry)
        {
            size_t pos = str.find("=");
            if (pos == std::string::npos)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 400; // BAD REQUEST
                return false;
            }
            std::string key = Util::UrlDecode(str.substr(0, pos), true);
            std::string val = Util::UrlDecode(str.substr(pos + 1), true);
            _request.SetParam(key, val);
        }
        return true;
    }

    bool ReciveHttpLine(Buffer *buf)
    {
        if (_recv_statu != RECV_HTTP_LINE)
        {
            lg.logmessage(Error, "%d _recv_statu is not RECV_HTTP_LINE", __LINE__);
        }
        std::string str = buf->GetLine(true);
        if (str.size() == 0)
        {
            if (buf->ReadableSzie() > MAX_LINE)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414; // url too long
                return false;
            }
            return true; // 等待数据
        }
        if (str.size() > MAX_LINE)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 414;
            return false;
        }
        bool ret = ParseHttpLine(str);
        if (ret == true)
        {
            _recv_statu = RECV_HTTP_HEAD; // 进入下一阶段
        }
        return ret;
    }

    bool ParseHttpHead(std::string &line)
    {
        // key: val\r\nkey: val\r\n....
        if (line.back() == '\n')
            line.pop_back(); // 末尾是换行则去掉换行字符
        if (line.back() == '\r')
            line.pop_back(); // 末尾是回车则去掉回车字符
        size_t pos = line.find(": ");
        if (pos == std::string::npos)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400; //
            return false;
        }
        std::string key = line.substr(0, pos);
        std::string val = line.substr(pos + 2);
        _request.SetHeader(key, val);
        return true;
    }
    bool ReciveHttpHead(Buffer *buf)
    {
        if (_recv_statu != RECV_HTTP_HEAD)
        {
            lg.logmessage(Error, "%d _recv_statu is not RECV_HTTP_HEAD", __LINE__);
            return false;
        }
        while (true)
        {
            std::string str = buf->GetLine(true);
            if (str.size() == 0)
            {
                if (buf->ReadableSzie() > MAX_LINE)
                {
                    _recv_statu = RECV_HTTP_ERROR;
                    _resp_statu = 414; // url too long
                    return false;
                }
                return true; // 等待数据
            }
            if (str.size() > MAX_LINE)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414;
                return false;
            }
            if (str == "\n" || str == "\r\n")

                break;

            bool ret = ParseHttpHead(str);
            if (ret == false)
                return false;
        }
        _recv_statu = RECV_HTTP_BODY;
        return true;
    }

    bool ReciveHttpBody(Buffer *buf)
    {
        if (_recv_statu != RECV_HTTP_BODY)
        {
            lg.logmessage(Error, "%d _recv_statu is not RECV_HTTP_BODY", __LINE__);
            return false;
        }
        size_t content_length = _request.ContentLength();
        if (content_length == 0)
        {
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        size_t real_len = content_length - _request._body.length(); // 需要再接收多少数据
        if (buf->ReadableSzie() >= real_len)                        // 缓冲区数据足够
        {
            _request._body.append(buf->GetReadPostion(), real_len);
            buf->MoveReadPostion(real_len);
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        else // 数据不够先读完
        {
            _request._body.append(buf->GetReadPostion(), buf->ReadableSzie());
            buf->MoveReadPostion(buf->ReadableSzie());
            return true;
        }
    }

public:
    HttpConntext() : _recv_statu(RECV_HTTP_LINE), _resp_statu(200) {}
    void Reset()
    {
        _recv_statu = RECV_HTTP_LINE;
        _resp_statu = 200;
        _request.Reset();
    }
    int RespStatu() { return _resp_statu; }
    HttpRecvStatu RecvStatu() { return _recv_statu; }
    HttpRequest &Request() { return _request; }
    void RecvHttpquest(Buffer *buf)
    {
        // std::cout<<"i am here"<<std::endl;
        // lg.logmessage(Debug,"ia am");
        switch (_recv_statu)
        {
        case RECV_HTTP_LINE:
            ReciveHttpLine(buf);
        case RECV_HTTP_HEAD:
            ReciveHttpHead(buf);
        case RECV_HTTP_BODY:
            ReciveHttpBody(buf);
            break;
        }
        
    }
};

class HttpServer
{
private:
    using Handler = std::function<void(const HttpRequest &, HttpResponse *)>;
    using Handlers = std::vector<std::pair<std::regex, Handler>>;
    Handlers _get_route;
    Handlers _post_route;
    Handlers _put_route;
    Handlers _delete_route;
    std::string _basedir; // 静态资源根目录
    TcpServer _server;

private:
    void ErrorHandler(const HttpRequest &req, HttpResponse *rsp)
    {
        // 1. 组织一个错误展示页面
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(rsp->_statu);
        body += " ";
        body += Util::DesStau(rsp->_statu);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        // 2. 将页面数据，当作响应正文，放入rsp中
        rsp->SetContent(body, "text/html");
    }
    bool IsFileHandler(const HttpRequest &req)
    {
        // 1. 必须设置了静态资源根目录
        if (_basedir.empty())
        {
            return false;
        }
        // 2. 请求方法，必须是GET / HEAD请求方法
        if (req._method != "GET" && req._method != "HEAD")
        {
            return false;
        }
        // 3. 请求的资源路径必须是一个合法路径
        if (Util::ValidPath(req._path) == false)
        {
            return false;
        }
        // 4. 请求的资源必须存在,且是一个普通文件
        //    有一种请求比较特殊 -- 目录：/, /image/， 这种情况给后边默认追加一个 index.html
        // index.html    /image/a.png
        // 不要忘了前缀的相对根目录,也就是将请求路径转换为实际存在的路径  /image/a.png  ->   ./wwwroot/image/a.png
        std::string req_path = _basedir + req._path; // 为了避免直接修改请求的资源路径，因此定义一个临时对象
        if (req._path.back() == '/')
        {
            req_path += "index.html";
        }
        if (Util::IsRegular(req_path) == false)
        {
            return false;
        }
        return true;
    }
    // 静态资源的请求处理 --- 将静态资源文件的数据读取出来，放到rsp的_body中, 并设置mime
    void FileHandler(const HttpRequest &req, HttpResponse *rsp)
    {
        std::string req_path = _basedir + req._path;
        if (req._path.back() == '/')
        {
            req_path += "index.html";
        }
        bool ret = Util::ReadFile(req_path, &rsp->_body);
        if (ret == false)
        {
            return;
        }
        std::string mime = Util::ExtMime(req_path);
        rsp->SetHeader("Content-Type", mime);
        return;
    }
    // 功能性请求的分类处理
    void Dispatcher(HttpRequest &req, HttpResponse *rsp, Handlers &handlers)
    {
        // 在对应请求方法的路由表中，查找是否含有对应资源请求的处理函数，有则调用，没有则发挥404
        // 思想：路由表存储的时键值对 -- 正则表达式 & 处理函数
        // 使用正则表达式，对请求的资源路径进行正则匹配，匹配成功就使用对应函数进行处理
        //   /numbers/(\d+)       /numbers/12345
        for (auto &handler : handlers)
        {
            const std::regex &re = handler.first;
            const Handler &functor = handler.second;
            bool ret = std::regex_match(req._path, req._matchs, re); // 对path进行正则匹配放到matchs
            if (ret == false)
            {
                continue;
            }
            return functor(req, rsp); // 传入请求信息，和空的rsp，执行处理函数
        }
        rsp->_statu = 404;
    }
    void Route(HttpRequest &req, HttpResponse *rsp)
    {
        // 1. 对请求进行分辨，是一个静态资源请求，还是一个功能性请求
        //    静态资源请求，则进行静态资源的处理
        //    功能性请求，则需要通过几个请求路由表来确定是否有处理函数
        //    既不是静态资源请求，也没有设置对应的功能性请求处理函数，就返回405
        if (IsFileHandler(req) == true)
        {
            // 是一个静态资源请求, 则进行静态资源请求的处理
            return FileHandler(req, rsp);
        }
        if (req._method == "GET" || req._method == "HEAD")
        {
            return Dispatcher(req, rsp, _get_route);
        }
        else if (req._method == "POST")
        {
            return Dispatcher(req, rsp, _post_route);
        }
        else if (req._method == "PUT")
        {
            return Dispatcher(req, rsp, _put_route);
        }
        else if (req._method == "DELETE")
        {
            return Dispatcher(req, rsp, _delete_route);
        }
        rsp->_statu = 405; // Method Not Allowed
        return;
    }
    void WriteReponse(const ConnectionPtr &conn, HttpRequest &req, HttpResponse &rsp)
    {
         
        // 1. 先完善头部字段
        if (req.Close() == true)
        {
            rsp.SetHeader("Connection", "close");
        }
        else
        {
            rsp.SetHeader("Connection", "keep-alive");
        }
        if (rsp._body.empty() == false && rsp.HasHeader("Content-Length") == false)
        {
            rsp.SetHeader("Content-Length", std::to_string(rsp._body.size()));
        }
        if (rsp._body.empty() == false && rsp.HasHeader("Content-Type") == false)
        {
            rsp.SetHeader("Content-Type", "application/octet-stream");
        }
        if (rsp._redirect_flag == true)
        {
            rsp.SetHeader("Location", rsp._redirect_url);
        }
        // 2. 将rsp中的要素，按照http协议格式进行组织
        // HTTP/1.1 200 OK\r\n
        std::stringstream rsp_str;
        rsp_str << req._version << " " << std::to_string(rsp._statu) << " " << Util::DesStau(rsp._statu) << "\r\n";
        for (auto &head : rsp._headers)
        {
            rsp_str << head.first << ": " << head.second << "\r\n";
        }
        rsp_str << "\r\n";
        rsp_str << rsp._body;
        lg.logmessage(Debug, "%s", rsp_str.str().c_str());
        // 3. 发送数据
        conn->Send(rsp_str.str().c_str(), rsp_str.str().size());
    }

    // 设置上下文
    void OnConnected(const ConnectionPtr &conn)
    {
        conn->SetContext(HttpConntext());
        lg.logmessage(Debug, "neew connection %p", conn.get());
    }
    void OnMessage(const ConnectionPtr &conn, Buffer *buf)
    {
        while (buf->ReadableSzie() > 0)
        {
            HttpConntext *context = conn->GetContext()->Get<HttpConntext>(); // 获取上下文
            context->RecvHttpquest(buf);                                     // 对缓冲区做上下文分析
            HttpRequest &req = context->Request();
            HttpResponse rsp(context->RespStatu());
            if (context->RespStatu() >= 400)
            {
                // std::cout<<"ppp"<<std::endl;
                ErrorHandler(req, &rsp);                   // 填写错误页面到响应
                WriteReponse(conn, req, rsp);              // 发送给客户端
                context->Reset();                          // 将其重置因为
                buf->MoveReadPostion(buf->ReadableSzie()); // 出错了就把缓冲区数据清空
                conn->Shutdown();                          // 关闭链接
                return;
            }
            if (context->RecvStatu() != RECV_HTTP_OVER) // 对面数据没发完
            {
                return;
            }
            Route(req, &rsp);
            WriteReponse(conn, req, rsp);
            if (rsp.Close()) // 由自己确定长短链接
            {
                conn->Shutdown();
                return;
            }
            context->Reset();
        }
    }

public:
    HttpServer(uint16_t port, int thread_count = 1) : _server(port, thread_count)
    {
        _server.EnableInactiveRelease(DEFAULT_TIME_OUT);
        _server.SetConnectedCallback(std::bind(&HttpServer::OnConnected, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&HttpServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
    }

    void SetBaseDir(const std::string &path)
    {
        assert(Util::IsDirectory(path) == true);
        _basedir = path;
    }
    /*设置/添加，请求（请求的正则表达）与处理函数的映射关系*/
    void Get(const std::string &pattern, const Handler &handler)
    {
        _get_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Post(const std::string &pattern, const Handler &handler)
    {
        _post_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Put(const std::string &pattern, const Handler &handler)
    {
        _put_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Delete(const std::string &pattern, const Handler &handler)
    {
        _delete_route.push_back(std::make_pair(std::regex(pattern), handler));
    }
    void Listen()
    {
        _server.Start();
    }
};
